package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.example.exception.CustomException;
import com.example.mapper.CommentMapper;
import com.example.mapper.RoomImageMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.RoomTypeMapper;
import com.example.pojo.Account;
import com.example.pojo.Room;
import com.example.pojo.RoomImage;
import com.example.pojo.RoomType;
import com.example.service.RoomService;
import com.example.util.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class RoomServiceImpl implements RoomService {
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private RoomImageMapper roomImageMapper;
    @Resource
    private RoomTypeMapper roomTypeMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 为房间添加图片
     */
    public void addImagesToRoom(List<Room> rooms)  {
        for (Room room:rooms){
            List<RoomImage> roomImages = roomImageMapper.selectById(room.getId());
            room.setRoomImages(roomImages);
        }
    }

    /**
     * 添加房间
     *
     * @param room
     */
    @Override
    @Transactional // 添加事务注解
    public void add(Room room) {
        room.setCommentCount(0);
        roomMapper.add(room);
        Integer roomId = room.getId();

        List<RoomImage>  roomImages = room.getRoomImages();
        if (roomImages!=null && !roomImages.isEmpty()){
            for (RoomImage roomImage:roomImages){
                roomImage.setRoomId(roomId);
                roomImageMapper.add(roomImage);
            }
        }


    }

    /**
     * 查询所有房间
     *
     * @return
     */
    @Override
    public List<Room> selectAll(String token,String keyword,String status,Integer typeId,Integer roomId) {
        Map<String,Object> claims = JwtUtil.parseToken(token);
        String role = (String) claims.get("role");
        Integer loginUserId = (Integer) claims.get("id");
        if ("user".equals(role)){
                status = "0";
        }
        // 新增ownerId参数，房东只查自己房间
        Integer ownerId = "owner".equals(role) ? loginUserId : null;

        List<Room> list = roomMapper.selectRoomByRole(role,keyword,status,typeId,ownerId,roomId);
        // 更新每个房间的评论数量
        for (Room room1 : list) {
            int count = commentMapper.countByRoomId(room1.getId());
            room1.setCommentCount(count);
            roomMapper.updateCommentCount(room1.getId(),count);
        }
        return list;
    }

    /**
     * 根据id查询房间
     *
     * @param id
     * @return
     */
    @Override
    public Room selectById(Integer id) {
        Room room = roomMapper.selectById(id);
        return room;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        Room room = roomMapper.selectById(id);
        if (room!=null){
            roomImageMapper.deleteById(id);
            roomMapper.deleteById(id);
        }else {
            throw new CustomException("500","(RoomSeriviceImpl--deleteById异常)房间不存在");
        }


    }

    /**
     * 批量删除数据
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id:ids){
            Room room = roomMapper.selectById(id);
            roomImageMapper.deleteById(id);
            roomMapper.deleteById(id);
        }

    }

    /**
     * 修改房间
     *
     * @param room
     */
    @Override
    public void updateById(Room room) {
        roomMapper.updateById(room);
    }

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Room> selectPage(Room room, Integer pageNum, Integer pageSize,
                                     @RequestHeader("Authorization") String token,
                                     String keyword, String status,Integer typeId) {
        // 验证token
        if (StrUtil.isBlank(token)) {
            throw new CustomException("401", "未登录");
        }

        // 验证token是否在redis中存在
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String redisToken = operations.get(token);
        if (StrUtil.isBlank(redisToken)) {
            throw new CustomException("401", "登录已过期");
        }

        try {
            // 从token中获取用户信息
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("id");
            String role = (String) claims.get("role");
            // 设置查询条件：只查询当前用户的房间


            // 执行分页查询
            PageHelper.startPage(pageNum, pageSize);
            List<Room> list = roomMapper.selectRoomByRole(role,keyword,status,typeId,userId,null);

            return PageInfo.of(list);
        } catch (Exception e) {
            log.error("解析token失败", e);
            throw new CustomException("401", "token无效");
        }

    }
}
